$(function () {
    event();
    $('select').selectpicker();
    //初始化数据库
    initDataSource();
});


function event() {
    //数据库选择
    $("#dms-config").on("change","#dataSourceCodes",function () {
        initTableRender();
        initCodeMirrorTables();
    });
}


function initDataSource() {
    $.ajax({
        url: "/datasource/query",
        async : false,
        success: function (data) {
            if(!data){return;}
            initDataSourceRender(data);
            initDataSourceTableColumn(data);
        }
    });
}
function initDataSourceRender (data) {
    var opts = [];
    opts.push("<option value=''>请选择</option>");
    for(var i = 0 ; i < data.length ; i++){
        opts.push("<option value='"+data[i].code+"'>"+data[i].code+"</option>");
    }
    var $ds = $("#dataSourceCodes");
    $ds.html(opts.join(""));
    $ds.selectpicker('refresh');
    $ds.data("dataSources",data);
}

function initDataSourceTableColumn(dataSources) {
    $.ajax({
        url: "/datasource/queryTableColumn",
        data: JSON.stringify(dataSources),
        method: "post",
        dataType: "json",
        contentType: 'application/json',
        success: function (data) {
            if(!data){ return ;}

            var codeMirrorTableColumn = {};
            var tables = {};
            for(var db in data){
                tables[db] = [];
                for(var table in data[db]){
                    codeMirrorTableColumn[table] = data[db][table];
                    codeMirrorTableColumn[db+"."+table] = data[db][table];
                    tables[db].push(table);
                }
            }
            $("#dataSourceCodes").data("codeMirrorTableColumn",codeMirrorTableColumn);
            $("#dataSourceCodes").data("tables",tables);
        }
    });
}


//初始化单表模式的表名
function initTableRender () {

    var db = $("#dataSourceCodes").val();
    var tables = $("#dataSourceCodes").data("tables");
    var array = db && tables ? tables[db] : [];
    var opts = [];
    for(var i = 0 ; i < array.length ; i++){
        opts.push("<option value='"+array[i]+"'>"+array[i]+"</option>");
    }
    var $table = $("#tables");
    $table.html(opts.join(""));
    $table.selectpicker('refresh');
}

//初始化codeMirror表提示
function initCodeMirrorTables() {

    var tables =  $("#dataSourceCodes").data("codeMirrorTableColumn");
    var codeMirror =  $("#mappedStatement").data("codeMirror");
    if(tables && codeMirror){
        var hintOptions =  codeMirror.getOption("hintOptions");
        hintOptions.tables = tables;
        codeMirror.setOption('hintOptions',hintOptions);
    }
}




